package com.goldmantis.activemq.ch2.jobs;

import java.util.Enumeration;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueBrowser;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Consumer2 {

    private static String brokerURL = "tcp://localhost:51616";
    private static transient ConnectionFactory factory;
    private transient Connection connection;
    private transient Session session;
    
    private String jobs[] = new String[]{"suspend"};
    
    public Consumer2() throws JMSException {
    	factory = new ActiveMQConnectionFactory(brokerURL);
    	connection = factory.createConnection();
    	connection.setClientID("queueConsumer");
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    }
    
    public void close() throws JMSException {
        if (connection != null) {
            connection.close();
        }
    }    
    
    public static void main(String[] args) throws JMSException {
    	Consumer2 consumer = new Consumer2();
    	Session session1 = consumer.getSession();
    	for (String job : consumer.jobs) {
    		Queue destination = consumer.getSession().createQueue("JOBS." + job);
            QueueBrowser browser = session1.createBrowser(destination);
            Enumeration<?> messages = browser.getEnumeration();
            while (messages.hasMoreElements()) {
            	ObjectMessage textMsg = (ObjectMessage) messages.nextElement();
                System.out.println(textMsg);
            }
            browser.close();
            consumer.close();
    	}
    }
	
	public Session getSession() {
		return session;
	}
}
